// router.js
import app from "main.js"
import {
	RouterMount,
	createRouter,
	runtimeQuit
} from 'uni-simple-router';

let loginStatus = null;
let appOnLaunch = 0;

const getJsCode = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: res => {
				resolve(res.code);
			},
			fail: err => {
				reject(err);
			}
		});
	})
}

const getUserInfo = async () => {
	let res = null;
	try {
		res = await app.$u.get("/v1/user/get_user_info");
		if (!res || res?.status != 1) {
			throw new Error(res.msg);
		}
		return new User(res?.data);
	} catch (e) {
		console.log(res);
		app.alert(e?.message || "授权接口请求失败");
		// throw new Error(e?.message || "请求接口失败");
	}
}

const app_lets_login = async (config) => {
	let res = null;
	try {
		res = await app.$u.post("/v1/auth/mp_app_login", {
			code: config.code,
			password: ""
		});
		if (!res || res.status != 1) {
			throw new Error(res.msg);
		}
		return res;
	} catch (e) {
		// uni.showToast({
		// 	title: "您已被禁用",
		// 	icon: 'error',
		// })
	}
}

const isLogin = function() {
	return new Promise(async (resolve, reject) => {
		try {
			const js_code = await getJsCode();
			const res = await app_lets_login({
				code: js_code,
				password: ''
			})
			resolve(res);
		} catch (e) {
			reject(e);
		}
	})
}

class User {
	constructor(obj) {
		console.log('用户模型');
		console.log(obj);
		this.id = obj?.id || 1;
		this.userIcon = obj?.user_icon;
		this.nickname = obj?.nickname || "融化月亮";
		this.isVerifier = obj?.is_verifier || true;
	}
}


const login = async function(to, from, next) {
	let res = await isLogin();
	console.log(res);
	if (res?.status == 1) {
		console.log('set token...')
		uni.setStorageSync('token', res.data.token)
		res = await getUserInfo();
		console.log(res)
		app.$u.vuex('userInfo', res);
	} else {
		try {
			uni.removeStorageSync('token');
		} catch (e) {
			throw new Error('登录失败');
		}
	}
	next()
}

const loginToPage = async function(to, from, next) {
	var token = null
	try {
		token = uni.getStorageSync('token')
	} catch (e) {}
	if (token == null) {
		const res = await isLogin();
		const data = res.data;
		if (data.code === 0 && data.data.token) {
			uni.setStorageSync('token', data.data.token)
			token = data.data.token
		}
	}
	if (token) {
		next();
	} else { //未登录 直接放行到登录页面
		if (to.name != 'login') {
			next({
				name: 'login',
				NAVTYPE: 'push'
			});
		} else {
			next();
		}
	}
}

const router = createRouter({
	platform: process.env.VUE_APP_PLATFORM,
	encodeURI: false,
	routerErrorEach: ({
		type,
		msg
	}) => {
		console.log({
			type,
			msg
		})
		// #ifdef APP-PLUS
		if (type === 3) {
			router.$lockStatus = false;
			runtimeQuit();
		}
		// #endif
		router.$lockStatus = false;
		uni.switchTab({
			url: 'pages/home/home'
		})

	},
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach(async (to, from, next) => {
	console.log(111111)
	if (appOnLaunch === 0) {
		console.log('login...')
		await login(to, from, next)
	} else {
		if (to.meta.auth) {
			await loginToPage(to, from, next);
		} else {
			next();
		}
	}
	console.log('...')
	appOnLaunch++;

});
// 全局路由后置守卫
router.afterEach((to, from) => {
	console.log('跳转结束')
})

export {
	router,
	RouterMount
}
